package qc.module.qms.logger;

import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import qc.common.core.constants.QmsMQConstant;
import qc.common.core.utils.LocalDateTimeUtil;
import qc.common.core.utils.QmsTimeUtil;
import qc.module.qms.dto.mq.QmsMqDataFlowLogMessageDto;
import qc.module.qms.service.log.QmsLogDataflowService;

/**
 * QMS数据流程日志Consumer，保存流程日志到数据库
 *
 * @author QuCheng Tech
 * @since 2025/8/22
 */
@Component
@RocketMQMessageListener(
        topic = QmsMQConstant.MQ_LOG_DATAFLOW_TOPIC,
        consumerGroup = QmsMQConstant.MQ_LOG_DATAFLOW_CONSUMER_SAVETODB_GROUP
)
public class QmsDataFlowLogConsumer implements RocketMQListener<QmsMqDataFlowLogMessageDto> {
    private static final Logger logger = LoggerFactory.getLogger(QmsDataFlowLogConsumer.class);

    @Autowired
    private QmsLogDataflowService logDataflowService;

    @Override
    public void onMessage(QmsMqDataFlowLogMessageDto message) {
        if (message != null) {
            try {
                logger.debug("onMessage 数据流程日志保存，当前节点ID[" + message.getNodeid() + "]，流程全局ID[" + message.getFlowid() + "]，来源节点ID[" + message.getFromnodeid()
                        + "]，点号[" + message.getPointid() + "]，时段类型[" + message.getPointtmseg() + "]，点号数据时间段[" + QmsTimeUtil.format(message.getPointbegintm(), message.getPointtmseg())
                        + "]-[" + QmsTimeUtil.format(message.getPointendtm(), message.getPointtmseg()) + "]，操作类型[" + message.getOptype() + "]，是否为人工操作[" + message.isIsmanual()
                        + "]，操作说明[" + message.getOpinfo() + "]，节点处理时间[" + LocalDateTimeUtil.formatDateTime(message.getBegintm())
                        + "]-[" + LocalDateTimeUtil.formatDateTime(message.getEndtm()) + "]，处理是否成功[" + message.isIssuccess() + "]，处理结果说明[" + message.getOpresult() + "]");

                //调用流程日志Service新增日志记录
                logDataflowService.addLog(message);
            } catch (Exception ex) {
                logger.error("根据MQ中的流程日志消息保存到数据库时异常，" + ex.getMessage());
            }
        }
    }
}
